package cn.crc.pjblog.services;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.tapestry.Link;
import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.internal.services.LinkFactory;
import org.apache.tapestry.internal.services.PageMarkupRenderer;
import org.apache.tapestry.internal.services.PageResponseRenderer;
import org.apache.tapestry.internal.services.RequestPageCache;
import org.apache.tapestry.internal.structure.Page;

import org.apache.tapestry.ioc.MappedConfiguration;

import org.apache.tapestry.ioc.OrderedConfiguration;


import org.apache.tapestry.ioc.annotations.InjectService;
import org.apache.tapestry.ioc.annotations.SubModule;
import org.apache.tapestry.ioc.annotations.Symbol;

import org.apache.tapestry.services.ComponentClassResolver;
import org.apache.tapestry.services.MarkupWriterFactory;
import org.apache.tapestry.services.Request;
import org.apache.tapestry.services.RequestExceptionHandler;
import org.apache.tapestry.services.RequestFilter;
import org.apache.tapestry.services.RequestGlobals;
import org.apache.tapestry.services.RequestHandler;

import org.apache.tapestry.services.Response;


import cn.crc.spring.SpringModule;



@SubModule(SpringModule.class)
public class AppModule {

	
    //解决页面显示的中文问题 
	
    public static PageResponseRenderer decoratePageResponseRenderer(  
            @InjectService("PageMarkupRenderer")  
            final PageMarkupRenderer markupRenderer,  
            @InjectService("MarkupWriterFactory")  
            final MarkupWriterFactory markupWriterFactory, final Object delegate) {   
    		return new PageResponseRenderer() {  
            public void renderPageResponse(Page page, Response response)  
                    throws IOException {  
                MarkupWriter writer = markupWriterFactory.newMarkupWriter();  
                markupRenderer.renderPageMarkup(page, writer);  
               
                PrintWriter pw = response.getPrintWriter("text/html; charset=UTF-8");  
                writer.toMarkup(pw);  
                pw.flush();  
            }  
        };  
    }  
    
//  表单输入的CJK(中文)支持   
    public void contributeRequestHandler(   
            OrderedConfiguration configuration,   
            @InjectService("EncodingFilter")   
            RequestFilter encodingFilter) {   
        configuration.add("EncodingFilter", encodingFilter);   
    }   
  
    public RequestFilter buildEncodingFilter(
  
    @InjectService("RequestGlobals")   
    final RequestGlobals requestGlobals) {   
        return new RequestFilter() {   
            public boolean service(Request request, Response response,   
                    RequestHandler handler) throws IOException {   
            	requestGlobals.getHTTPServletRequest().setCharacterEncoding("UTF-8");   
                
            	return handler.service(request, response);   
            }   
        };   
    }   
//	@Contribute("tapestry.ioc.ApplicationDefaults")
    public static void contributeApplicationDefaults(
            MappedConfiguration<String, String> configuration)
    {
        // Contributions to tapestry.ioc.ApplicationDefaults will override any contributes to
        // tapestry.io.FactoryDefaults (with the same key). Here we're restricting the supported locales
        // to just "en" (English). Tapestry will be most efficient with a finite number of supported locales.
        // As you add localised message catalogs and other assets, you can extend this list of locales (it's
        // a comma seperated series of locale name; the first locale name is the default when there's no
        // reasonable match).
    	
    	//tapestry.default-cookie-max-age  秒为单位，默认一周
    	//tapestry.file-check-interval 文件检查间隔 单位毫秒 millisecond 默认一秒
    	//apestry.scriptaculous  The path to the embedded copy of script.aculo.us packaged
    	//设置上传文件的公用路径
//    	 configuration.add("tutor.file-system-root", "/Users/pbeshai/tmproot/");
    	//in components code 
//    	@Inject
//    	@Value("${tutor.file-system-root}")
//    	private String fileSystemRoot;
    	
        configuration.add("tapestry.supported-locales", "zh");
        configuration.add("tapestry.start-page-name", "login");
        
    }
    
   
   
    
   
//     public static CommonPublicDAO buildCommonPublicDAO(   
//                @InjectService("Session")   
//               Session session,Log log) {   
//    	 
////    	 System.out.println("启动T5的H3 build");
//            return new CommonPublicDAOImpl(session);   
//       }   
//    public static void bind(ServiceBinder binder){
////    	System.out.println("启动T5的H3bind");
//    	binder.bind(CommonPublicDAO.class,CommonPublicDAOImpl.class);
//    	binder.bind(MyService.class,MyServiceImpl.class);
//    	binder.bind(MyAnotherService.class,MyAnotherServiceImpl.class);    	
//    	
//    }
//    public static MyAnotherService decorateMyAnotherService(
//    		Object delegate,MyService myService,Log log
//    ){    	
//    	return new Interceptor((MyAnotherService)delegate,myService,log);
//    }
//配置ASO
//    	public void contributeApplicationStateManager(MappedConfiguration <Class, ApplicationStateContribution> configuration){
//    		System.out.println("Create ApplicationState BlogMember");
//    		ApplicationStateCreator<BlogMember> creator  = new ApplicationStateCreator<BlogMember>()
//    		{
//    			public BlogMember create(){
//    				System.out.println("Create ApplicationState BlogMember");
//    				return new BlogMember();
//    			}
//    			
//    		};
//    		configuration.add(BlogMember.class, new ApplicationStateContribution("session",creator));
//    		
//    	}
    	
//     handle redirectException
    	/**
    	 * handle redirectException
    	 * @see http://wiki.apache.org/tapestry/Tapestry5RedirectException
    	 * Add this method to your AppModule.java
    	 * */
    	public static RequestExceptionHandler decorateRequestExceptionHandler(
    			final Object delegate, final Response response,
    	        final RequestPageCache requestPageCache, final LinkFactory linkFactory,
    	        final ComponentClassResolver resolver
    	){
    		
    		return new RequestExceptionHandler(){
    			
    			public void handleRequestException(Throwable excep) 
    				throws IOException{
    				// checked if wappered
    				Throwable cause = excep;
    				
    				if (excep.getCause() instanceof RedirectException){
    					
    					cause = excep.getCause();
    				}
    				//check for direct
    				
    				if (cause instanceof RedirectException){
    					//check for class and string
    					
    					RedirectException re =(RedirectException) cause;
    					Link pageLink = re.getPageLink();
    					
    					if (pageLink == null){
    						//handler class see ClassResultProcessor
    						String pageName = re.getMessage();
    						Class<?> pageClass = re.getPageClass();
    						if (pageClass != null){
    							
    							pageName = resolver.resolvePageClassNameToPageName(pageClass.getName());
    						}
    						// handle String (see StringResultProcessor)
    						Page page = requestPageCache.get(pageName);
                            pageLink = linkFactory.createPageLink(page, false);
    						
    						
    					}
//    					 handle Link redirect
                        if (pageLink != null)
                        {
                            response.sendRedirect(pageLink.toRedirectURI());
                            return;
                        }
    				}    				
//    				 no redirect so pass on the exception
                    ((RequestExceptionHandler)delegate).handleRequestException(excep);
    				
    			}  			
    			
    		};
    	}
    	 public static void contributeFactoryDefaults(MappedConfiguration<String, String> configuration)
    	    {
    	        // This is designed to make it easy to keep syncrhonized with jscalendar. As we
    	        // support a new version, we create a new folder, and update the path entry. We can then
    	        // delete the old version folder (or keep it around). This should be more manageable than
    	        // ovewriting the local copy with updates. There's also a ClasspathAliasManager
    	        // contribution based on the path.

             configuration.add("componentimages", "classpath:${componentimages.path}");
             configuration.add("componentimages.path", "cn/crc/pjblog/components/images");
    	    }
    	/**
    	 * simplified path for components'images
    	 * @author doublel
    	 * 2007.09.07
    	 * */
    	
    	public static void contributeClasspathAssetAliasManager(
                MappedConfiguration<String, String> configuration,
                @Symbol("componentimages.path")
                String javaComponentImagesPath)
        {
    		System.out.println("simplified path for components's images initialize");
  
            configuration.add("ImagesPath/", javaComponentImagesPath+"/");
          
        }	
}
